<?php

namespace Jammiest\SwigeCore\Console\Commands\Server;


use Jammiest\SwigeCore\Console\Commands\Command;
use Jammiest\SwigeCore\Servers\ServerFactory;
use Jammiest\SwigeCore\Tools\Config;
use Jammiest\SwigeCore\Tools\Path;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Swoole\Http\Server;

#[AsCommand(name: 'server:start', description: 'start Swoole server')]
class StartCommand extends Command
{
    private $server;

    public function setContainer(ContainerInterface $container): void
    {
        $this->container = $container;
    }

    protected function getContainer(): ContainerInterface
    {
        return $this->container;
    }

    protected function configure()
    {
        $this->addOptions([
            'type' => Config::get('server.type','http'),
            'host' => Config::get('server.host','0.0.0.0'), 
            'port' => Config::get('server.port',9501),
            'workers' => Config::get('server.workers',swoole_cpu_num()),
            'task_workers' => Config::get('server.task_workers',swoole_cpu_num()),
            'daemon' => Config::get('server.daemon',false)
        ]);
    }

    private function addOptions(array $defaults)
    {
        $this->addOption('type', null, InputOption::VALUE_OPTIONAL, 'type:', $defaults['type'])
            ->addOption('host', null, InputOption::VALUE_OPTIONAL, 'host:', $defaults['host'])
            ->addOption('port', 'p', InputOption::VALUE_OPTIONAL, 'port:', $defaults['port'])
            ->addOption('workers', 'w', InputOption::VALUE_OPTIONAL, 'workers:', $defaults['workers'])
            ->addOption('task-workers', 't', InputOption::VALUE_OPTIONAL, 'task_workers:', $defaults['task_workers'])
            ->addOption('daemon', 'd', InputOption::VALUE_NONE, 'daemon:'. ($defaults['daemon'] ? 'true' : 'false'));
    }



    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $factory = new ServerFactory($this->container);
        $type = $input->getOption('type');
        $config = $this->container->get('config.server');
        $config['host'] = $input->getOption('host') ?? $config['host'];
        $config['port'] = (int)$input->getOption('port') ?? $config['port'];
        $config['settings']['worker_num'] = (int)$input->getOption('workers') ?? $config['settings']['worker_num'];
        $config['settings']['task_worker_num'] = (int)$input->getOption('task-workers') ?? $config['settings']['task_worker_num'];
        $config['settings']['daemonize'] = $input->getOption('daemon') ? 1 : ($config['settings']['daemonize'] ?? 0);
        $config['settings']['pid_file'] = Path::getBasePath('storage/swoole.pid') ?? ($config['settings']['pid_file'] ?? '');
        $config['settings']['log_file'] = Path::getBasePath('storage/logs/swoole.log') ?? ($config['settings']['log_file'] ?? '');
        $config['settings']['max_request'] = $config['settings']['max_request'] ?? 10000;
        $config['settings']['dispatch_mode'] = $config['settings']['dispatch_mode'] ?? 2;
        $config['settings']['enable_coroutine'] = $config['settings']['enable_coroutine'] ?? true;
        $server = $factory->create($type,$config); // 关键修改点

        $server->start();

        return Command::SUCCESS;
    }

    public function shutdownServer()
    {
        if ($this->server) {
            $this->server->shutdown();
        }
    }

    // WebSocket处理器示例
    protected function handleWebSocket($request, $response)
    {
        $response->header('Content-Type', 'application/json');
        $response->end(json_encode([
            'status' => 'success',
            'service' => 'websocket',
            'timestamp' => microtime(true)
        ]));
    }

    public function handleTask(Server $server, int $taskId, int $srcWorkerId, $data)
    {
        // 示例任务处理
        try {
            return ['status' => 'success', 'data' => $data];
        } catch (\Throwable $e) {
            return ['status' => 'error', 'message' => $e->getMessage()];
        }
    }

    public function handleTaskFinish(Server $server, int $taskId, $data)
    {
        // 可选的任务完成处理
        file_put_contents(
            Path::getBasePath('storage/logs/tasks.log'),
            json_encode($data) . PHP_EOL,
            FILE_APPEND
        );
    }
}
